#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/AGENT/lib -I/data/Software/mydan/AGENT/private/lib
use strict;
use warnings;

use FindBin qw( $RealBin );

use YAML::XS;
use Data::Dumper;

use Code;
use Logs;
use Util;


$| ++;

=head1 SYNOPSIS

    db => $mysql,
    uuid => 'uuid',

    logs => 日志对象

=cut

return sub
{
    my %param = @_;
    my ( $db, $uuid, $logs ) = @param{qw(db uuid logs )};

    $logs = Logs->new( 'code.install.plugin.import_proxy' ) unless $logs;

    $logs->die( "uuid format error" ) unless $uuid =~ /^[a-zA-Z0-9]+$/;

    my $x = eval{ $db->query( "select projectid,regionid,ip from install where uuid='$uuid'" );};
    $logs->die( "get install info from mysql fail install uuid=$uuid: $@" ) if $@;
    $logs->die( "get install info from mysql fail install uuid=$uuid" ) unless defined $x && ref $x eq 'ARRAY';
    $logs->die( "install uuid mismatch uuid=$uuid" ) unless @$x;

    my ( $projectid, $regionid, $ip ) = @{$x->[0]};

    my @ip = grep{ /^[a-zA-Z0-9_\-\.]+$/ }split /,| /, $ip;

    print Dumper \@ip;

    my %reason = %Util::reason;

    my $install = eval{ YAML::XS::LoadFile "$RealBin/../conf/install" };
    $logs->die( "load install fail from conf/install:$@" ) if $@;
    $logs->die( "conf/install no get_proxy_version" ) unless $install->{get_proxy_version};

    for my $node ( @ip )
    {
        my $starttime = POSIX::strftime( "%Y-%m-%d %H:%M:%S", localtime );
        eval{ $db->execute( "replace into install_detail (`uuid`,`ip`,`type`,`starttime`,`finishtime`,`status`,`reason`) 
                values( '$uuid', '$node', 'proxy', '$starttime','','','' )" ); };

        my ( $status, $reason, $version ) = ( 'success', '', 0 );

        my $get_proxy_version = $install->{get_proxy_version};
        $get_proxy_version =~ s/__NODE__/$node/g;

        print "get_proxy_version: $get_proxy_version 2>&1\n";
        my $vcont = `$get_proxy_version 2>&1`;
        print "get_proxy_version: $vcont\n";

        if( $vcont =~ /file version:(\d+)/  )
        {
            $version = $1;
        }
        else
        {
             ( $status, $reason ) = ( 'fail', 'unkown error' );

            for my $k ( keys %reason )
            {
                if( $vcont =~ /$k/ )
                {
                    $reason = $reason{$k};
                    last;
                }
            }
        }
        

        my $finishtime = POSIX::strftime( "%Y-%m-%d %H:%M:%S", localtime );
        eval{ $db->execute( "update install_detail set finishtime='$finishtime',status='$status',reason='$reason' where uuid='$uuid' and ip='$node'" ); };
        $logs->die( "update install_detail info fail:$@" ) if $@;

        eval{ $db->execute( "replace into proxy(`regionid`,`ip`,`status`,`version`,`projectid`) values( '$regionid', '$node', '$status', '$version', '$projectid' )" ) if $status eq 'success' };
        $logs->die( "update install status fail:$@" ) if $@;
    }

    return 'success';
}
